<?php
/**
 * 优惠券管理
 * edition ：v1
 * create time：2021-06-08
 * author: acker
 */
namespace App\Admin\Controllers\Coupon;


use App\Http\Controllers\Controller;
use App\Models\DataDictionaryModel;
use App\Models\yb\CouponDispatchRecordModel;
use App\Models\yb\CouponModel;
use App\Models\yb\SmsModel;
use App\Models\yb\UserCouponModel;
use App\Models\yb\UserModel;
use Cisco\Aliyunsms\Facades\Aliyunsms;
use Encore\Admin\Form;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\MessageBag;


class DistributionController extends Controller
{
    use ModelForm;

    protected $header = '优惠券管理';

    /**
     * 新增
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header($this->header);
            $content->description('添加');
            $content->body($this->form());

        });
    }

    /**
     * @return mixed
     */
    public function form(){

        $form = new Form(new CouponDispatchRecordModel());

        $form->radio('type', '用户类型')
            ->options(DataDictionaryModel::CouponDispatchType)->when(2, function (Form $form) {
                $form->multipleSelect('user_id', '选择用户')->options(UserModel::selectOptions())->rules('required');
            })->when(3, function (Form $form) {
                $form->dateRange('registration_start_time', 'registration_end_time', '日期范围')->rules('required');
            })->default(1);

        $form->select('coupon_id', '选择优惠券')->options(CouponModel::selectOptions())->rules('required');

        $form->select('sms_code', '提醒短信', '有效期')->options(SmsModel::selectOptions());

        $form->tools(function (Form\Tools $tools) {
            $tools->disableView();
        });

        $form->footer(function ($footer) {
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
        });

        //保存前回调
        $form->saving(function (Form $form) {

            $coupon_data = CouponModel::where(['id'=>$form->coupon_id,'status'=>1])->first();
            if(empty($coupon_data)){
                $error = new MessageBag([
                    'title'   => '警告',
                    'message' => '该优惠券已过期！',
                ]);
                return back()->with(compact('error'));
            }
        });

        //保存后回调
        $form->saved(function (Form $form) {
            
            if($form->model()->type == 1){
                $user = UserModel::select(['id','phone','openid'])->get()->toArray();
            }else if ($form->model()->type == 2){
                $user = UserModel::whereIn('id',$form->model()->user_id)->select(['id','phone','openid'])->get()->toArray();
            }else if($form->model()->type == 3){
                $user = UserModel::where('created_at','>=',$form->model()->registration_start_time)->where('created_at','<=',$form->model()->registration_start_time)->select(['id','phone','openid'])->get()->toArray();
            }

            if(!empty($form->model()->sms_code)){

                $phones = array_column($user, 'phone');

                $phone = array_unique($phones);

                $PhoneNumber = implode(",",$phone);

                $SignName    = "易宝到家";          //模板签名

                $TemplateCode= $form->model()->sms_code;         //模板CODE

                //阿里云模板里面的变量
                $TemplateParam = "";

                Aliyunsms::sendSms(strval($PhoneNumber), $SignName, $TemplateCode, $TemplateParam);
            }

            $coupon_id = $form->model()->coupon_id;

            foreach($user as $key=>$val){

                $coupon_data = CouponModel::where(['id'=>$coupon_id])->first();

                UserCouponModel::insert([
                    'user_id' => $val['id'],
                    'openid' => $val['openid'],
                    'goods_type' => $coupon_data['goods_type'],
                    'coupon_id' => $coupon_id,
                    'validity_start' => date('Y-m-d'),
                    'validity_end' => date('Y-m-d',strtotime("+".$coupon_data['validity_after']." day")),
                    'promotion_full' => $coupon_data['promotion_full'],
                    'promotion_reduce' => $coupon_data['promotion_reduce'],
                    'created_at' => date('Y-m-d H:i:s',time())
                ]);

                CouponModel::where(['id'=>$coupon_id])->increment('received_number');

            }

            return redirect('/admin/coupon/distribution/manage/create');
        });

        return $form;
    }

}
